package com.xushi.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xushi.bean.TemplateType;
import com.xushi.model.Template;
import com.xushi.model.TimePriceMap;
import com.xushi.service.StorageService;
import com.xushi.service.TemplateService;
import com.xushi.service.TimePriceMapService;
import com.xushi.service.impl.QRCodeGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/template")
public class TemplateController {

    private static final String templateQrCodeSuffix = "_template.png";
    private final StorageService storageService;
    @Autowired
    QRCodeGenerator qrCodeGenerator;

    @Autowired
    TemplateService templateService;

    @Autowired
    TimePriceMapService timePriceMapService;

    @Autowired
    public TemplateController(StorageService storageService) {
        this.storageService = storageService;
    }

    @RequestMapping(value = "generateQRCode", method = RequestMethod.GET)
    @ResponseBody
    public HashMap<String, Object> genQRCode(@RequestParam String templateName, @RequestParam String callback) {
        HashMap<String, Object> map = new HashMap<>();
        String fileName = templateName + ".png";
        boolean isSuccess = qrCodeGenerator.encode(fileName, callback);
        if (isSuccess) {
            map.put("code", 1);
            map.put("message", "generate qr code successfully");
        } else {
            map.put("code", 2);
            map.put("message", "fail to generate qr code");
        }
        return map;
    }

    @RequestMapping(value = "getQRCode", method = RequestMethod.GET)
    public void getQRCode(@RequestParam int templateId, HttpServletResponse response) throws IOException {
        try {
            String fileName = templateId + templateQrCodeSuffix;
            byte[] data = qrCodeGenerator.getQRCode(fileName);
            if (data != null) {
                response.setContentType("image/png");
                response.getOutputStream().write(data);
                return;
            }
        } catch (IOException ioe) {
            System.out.println(ioe);
        }
        response.getWriter().write("get QR code failed");
    }

    @PostMapping("/createTemplate")
    @ResponseBody
    public HashMap<String, Object> createTemplate(@RequestParam String templateName, @RequestParam String title,
                                                  @RequestParam String description,
                                                  @RequestParam("serveUrl") String serveUrl,
                                                  @RequestParam("type") String type,
                                                  @RequestParam("timePriceMap") String timePriceMap,
                                                  @RequestParam("backgroundImg") MultipartFile backgroundImg) {
        HashMap<String, Object> map = new HashMap<>();
        int templateId = 0;
        if (!TemplateType.validType(type)) {
            map.put("code", 2);
            map.put("message", "模版类型错误，支持h5和wechat");
            return map;
        }

        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        String username = userDetails.getUsername();

        if (backgroundImg.isEmpty()) {
            map.put("code", 3);
            map.put("message", "上传的背景图片不能为空");
            return map;
        }
        storageService.store(backgroundImg);

        String backgroundImgPath = backgroundImg.getOriginalFilename();


        try {
            Template template = templateService.createTemplate(username, templateName, title, description, serveUrl,
                    type, backgroundImgPath);
            templateId = template.getId();
            String filename = template.getId() + templateQrCodeSuffix;
            boolean isSuccess = qrCodeGenerator.encode(filename, serveUrl);
            if (!isSuccess) {
                map.put("code", 4);
                map.put("message", "fail to generate qr code");
                return map;
            }
        } catch (Exception e) {
            map.put("code", 5);
            map.put("message", e.toString());
            return map;
        }

        JSONArray json = JSONArray.parseArray(timePriceMap);
        if (json.size() < 4) {
            map.put("code", 6);
            map.put("message", "价格时间的设置错误");
            return map;
        }
        for (int i = 0; i < json.size(); i++) {
            JSONObject temp = json.getJSONObject(i);
            TimePriceMap isExist = timePriceMapService.findByTemplateIdAndTimeId("" + templateId, temp.get("timeId").toString());
            if (null != isExist) {
                map.put("code", 6);
                map.put("message", "error! the time is Exist");
                return map;
            }
            timePriceMapService.addTimePriceMap("" + templateId, temp.get("timeId").toString(), temp.get("price").toString());
        }


        map.put("code", 1);
        map.put("message", "create success!");
        return map;
    }


    @PostMapping("/updateTemplateText")
    @ResponseBody
    public HashMap<String, Object> updateTemplate(@RequestParam int templateId,
                                                  @RequestParam String templateName,
                                                  @RequestParam String title,
                                                  @RequestParam String description,
                                                  @RequestParam("serveUrl") String serveUrl,
                                                  @RequestParam("type") String type) {
        HashMap<String, Object> result = new HashMap<>();

        Template template = templateService.getTemplateById(templateId);
        if (ObjectUtils.isEmpty(template)) {
            result.put("code", 2);
            result.put("message", "模版不存在");
            return result;
        }
        try {
            template.setDescription(description);
            template.setTitle(title);
            template.setServeUrl(serveUrl);
            template.setType(type);
            template.setName(templateName);
            template = templateService.updateTemplate(template);
            result.put("code", 1);
            result.put("template", template);
        } catch (Exception e) {
            result.put("code", 2);
            result.put("message", e.toString());
        }
        return result;
    }

    @PostMapping("/replaceBackground")
    @ResponseBody
    public HashMap<String, Object> replaceBackground(@RequestParam int templateId,
                                                     @RequestParam("backgroundImg") MultipartFile backgroundImg) {
        HashMap<String, Object> result = new HashMap<>();

        Template template = templateService.getTemplateById(templateId);
        if (ObjectUtils.isEmpty(template)) {
            result.put("code", 2);
            result.put("message", "模版不存在");
            return result;
        }

        HashMap<String, Object> map = new HashMap<>();
        if (backgroundImg.isEmpty()) {
            map.put("code", 2);
            map.put("message", "上传的背景图片不能为空");
            return map;
        }
        storageService.store(backgroundImg);

        String backgroundImgPath = backgroundImg.getOriginalFilename();
        template.setBackgroundImgPath(backgroundImgPath);
        template = templateService.updateTemplate(template);
        result.put("code", 1);
        result.put("template", template);
        return result;
    }

    @GetMapping("/getTemplateByName")
    @ResponseBody
    public HashMap<String, Object> getTemplate(@RequestParam String templateName) {
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        String username = userDetails.getUsername();
        HashMap<String, Object> result = new HashMap<>();
        result.put("code", 1);
        Template template = templateService.getTemplate(username, templateName);
        if (ObjectUtils.isEmpty(template)) {
            result.put("code", 2);
            result.put("message", "template does not exist");
        } else {
            result.put("template", template);
        }
        return result;
    }

    @GetMapping("/getTemplateById")
    @ResponseBody
    public HashMap<String, Object> getTemplate(@RequestParam int templateId) {

        HashMap<String, Object> result = new HashMap<>();
        result.put("code", 1);
        Template template = templateService.getTemplateById(templateId);
        if (ObjectUtils.isEmpty(template)) {
            result.put("code", 2);
            result.put("message", "template does not exist");
        } else {
            result.put("template", template);
        }
        return result;
    }


    @GetMapping("getTemplateList")
    @ResponseBody
    public HashMap<String, Object> getTemplateList() {
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        String username = userDetails.getUsername();
        HashMap<String, Object> result = new HashMap<>();
        result.put("code", 1);
        List<Template> templateList = templateService.getTemplateListByUsername(username);
        if (CollectionUtils.isEmpty(templateList)) {
            result.put("code", 2);
            result.put("message", "用户没有创建模版");
        } else {
            result.put("templateList", templateList);
        }
        return result;
    }

    @GetMapping("getHomeTemplateList")
    @ResponseBody
    public HashMap<String, Object> getHomeTemplateList() {

        HashMap<String, Object> result = new HashMap<>();
        result.put("code", 1);
        List<Template> templateList = templateService.getTemplateListByUsername("admin");
        if (CollectionUtils.isEmpty(templateList)) {
            result.put("code", 2);
            result.put("message", "用户没有创建模版");
        } else {
            result.put("templateList", templateList);
        }
        return result;
    }
}
